<template xmlns="http://www.w3.org/1999/html">
  <div class="app-container">

    <el-form ref="formRef" :rules="rules" :model="form" label-width="140px">
      <div v-for="(item,index) in form.value" :key="index">
        <div>{{item.configName}}</div>
        <!-- <div v-for="(k, i) in item.configValue" :key="i"> -->
        <el-row class="row_wrapper">
          <!-- <div class="icon_delete" @click="iconDeleteFn(k, i)">
            <i class="el-icon-close"></i>
          </div> -->

          <el-col :span="6" v-for="(k, i) in item.configValue" :key="i">
            <el-form-item :label="k.teamLevel?'S'+k.teamLevel:i==0?'直推用户奖励':i==1?'2-9代用户奖励':i==2?'10-20代用户奖励':''"
              :prop="'value.'+index+ '.configValue.' + i + '.rewardPerStr'" :rules="{
                required: true,
                message: '请输入最小奖励',
                trigger: 'blur',
              }" v-if="index==0">
              <el-input-number :min="0" v-model="k.rewardPerStr" placeholder="请输入最小奖励" v-if="index==0" />
            </el-form-item>
            <el-form-item :label="k.teamLevel?'S'+k.teamLevel:i==0?'直推用户奖励':i==1?'2-9代用户奖励':i==2?'10-20代用户奖励':''"
              :prop="'value.'+index+ '.configValue.' + i +'.rewardPerStr'" :rules="{
                required: true,
                message: '请输入最小奖励',
                trigger: 'blur',
              }" v-if="index==1">
              <el-input-number :min="0" v-model="k.rewardPerStr" placeholder="请输入最小奖励" v-if="index==1" />
            </el-form-item>
            <el-form-item :label="k.teamLevel?'S'+k.teamLevel:i==0?'直推用户奖励':i==1?'2-9代用户奖励':i==2?'10-20代用户奖励':''"
              :prop="'value.'+index+ '.configValue.' + i + '.rewardAmt'" :rules="{
                required: true,
                message: '请输入最小奖励',
                trigger: 'blur',
              }" v-if="index==2">
              <el-input-number :min="0" v-model="k.rewardAmt" placeholder="请输入最小奖励" v-if="index==2" />
            </el-form-item>
            <el-form-item :label="k.teamLevel?'S'+k.teamLevel:i==0?'直推用户奖励':i==1?'2-9代用户奖励':i==2?'10-20代用户奖励':''"
              :prop="'value.'+index+ '.configValue.' + i + '.rewardPerStr'" :rules="{
                required: true,
                message: '请输入最小奖励',
                trigger: 'blur',
              }" v-if="index==3">

              <el-input-number :min="0" v-model="k.rewardPerStr" placeholder="请输入最小奖励" v-if="index==3" />
            </el-form-item>
          </el-col>

        </el-row>
        <!-- </div> -->

      </div>

      <!-- <el-form-item label="图标" prop="icon">
          <imageUpload :limit="1" :file-size="3" v-model="form.icon" />
        </el-form-item> -->
      <!-- <el-form-item label="任务状态" prop="openFlag">
        <el-radio v-model="form.openFlag" label="0" border>关闭</el-radio>
        <el-radio v-model="form.openFlag" label="1" border>开启</el-radio>
      </el-form-item> -->
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm('formRef')">确定</el-button>
      <el-button @click="cancel">重置</el-button>
    </div>

  </div>
</template>

<script>
import { deleteTaskInfo, getTaskPage, updateTaskInfo } from "@/api/admin/task";

export default {
  name: "TaskManage",
  data() {
    return {
      requestUrl: this.$img.requestUrl,
      activeName: "pending",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务详情表格数据
      taskList: [
        {
          orderNum: "1",
          taskName: "标题",
          description: "奖励说明",
          configJson: [
            {
              levelStr: "11",
              minReward: "22",
              maxReward: "33",
              taskCnt: "44",
            },
          ],
          openFlag: "1",
        },
      ],
      taskTypeList: [],
      // 弹出层标题

      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskType: 1,
      },
      // 表单参数
      form: { value: [] },
      optionsLevel: [
        {
          value: "1",
          label: "普通会员",
        },

      ],
      rules: {
        taskName: [
          { required: true, message: "请输入任务名", trigger: "blur" },
        ],
        taskCnt: [
          {
            required: true,
            message: "任务次数必须为正整数",
            trigger: "blur",
          },
        ],

        description: [
          { required: true, message: "请输入任务描述", trigger: "blur" },
        ],
        orderNum: [
          { required: true, message: "请输入任务排序", trigger: "blur" },
        ],
        icon: [{ required: true, message: "请上传图片", trigger: "blur" }],
        maxReward: [
          {
            required: true,
            message: "请输入最大奖励",
            trigger: "blur",
          },
          {
            type: "number",
            validator: (rule, value, callback) => {
              const replaces = rule.field.replace(/[^0-9]/g, "");
              if (value <= this.form.taskConfig[Number(replaces)].minReward) {
                callback(new Error("最大值不能低于最小值"));
              }
              callback();
            },
          },
        ],
      },
      detailDialogTableVisible: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 自定义校验函数 validateArray
    validateArray: (rule, value, callback, message) => {
      if (rule.length) {
        const index = rule.every((item) => {
          return item[value] > 0;
        });
        if (index) {
          callback();
        } else {
          callback(new Error(message));
        }
      }
    },

    //删除新增的规则
    iconDeleteFn(k, i) {
      this.form.taskConfig.splice(i, 1);
    },
    //删除新增的奖励配置
    iconDeleteRowFn(j, f) {
      this.form.rewardConfig.splice(f, 1);
    },
    //新增任务配置规则
    taskConfigFn() {
      const option = {
        taskLevel: "",
        minReward: "",
        maxReward: "",
        taskCnt: "",
      };
      try {
        if (this.form.taskConfig.length >= 10)
          return this.msgInfo("最多新增10条！");
        this.form.taskConfig.push(option);
      } catch (e) {
        this.form.taskConfig = [option];
      }
    },
    //新增奖励配置
    rewardConfigFn() {
      const data = {
        taskCnt: 1,
        rewardPer: 0,
      };
      try {
        if (this.form.rewardConfig.length >= 10)
          return this.msgInfo("最多新增10条！");
        this.form.rewardConfig.push(data);
      } catch (e) {
        this.form.rewardConfig = [data];
      }
    },
    //列表类型切换
    handleClick(tab, event) {
      let name = tab.name;
      if (name === "pending") {
        this.queryParams.taskType = 2;
      } else if (name === "pending2") {
        this.queryParams.taskType = 5;
      } else {
        this.queryParams.taskType = 3;
      }

      this.getList();
    },
    //新增
    handleAdd() {
      this.title = "新增任务";
      this.detailDialogTableVisible = true;
      //默认选中一个类型
      this.form = {
        openFlag: "1",
        taskType: this.queryParams.taskType + "",
        orderNum: 1,
        taskCnt: 1,
        taskConfig: [],
        rewardConfig: [],
      };
    },
    /** 查询任务详情列表 */
    getList() {
      this.loading = true;
      getTaskPage(this.queryParams).then((response) => {
        this.form.value = response.data;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.detailDialogTableVisible = false;
      this.getList()
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 编辑按钮操作 */
    handleView(row) {
      this.title = "编辑任务";
      this.getList();
      this.detailDialogTableVisible = true;
      this.form = {
        ...row,
        openFlag: String(row.openFlag),
        taskType: String(row.taskType),
      };
      this.form.taskConfig.forEach((item) => {
        item.taskLevel = String(item.taskLevel);
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {

          updateTaskInfo(JSON.stringify(this.form.value)).then((res) => {
            if (res.code === 200) {
              this.msgSuccess(res.msg);
              this.getList();
              this.cancel();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    close(row, openFlag) {
      const ids = row.taskId || this.ids;
      this.$confirm("确认关闭该任务吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return updateTaskInfo({
            taskId: ids,
            openFlag: openFlag,
          });
        })
        .then(() => {
          this.getList();
          this.msgSuccess("操作成功");
        })
        .catch(function () { });
    },
    deleteApiFn(row, openFlag) {
      const ids = row.taskId || this.ids;
      this.$confirm("确认删除该任务吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return deleteTaskInfo({
            taskId: ids,
          });
        })
        .then((res) => {
          this.getList();
          this.msgSuccess("操作成功");
        })
        .catch(function () { });
    },
  },
};
</script>
<style lang="scss" scoped>
.dialog-footer {
  width: 100%;
  display: flex;
  justify-content: center;
}
.row_wrapper {
  display: block;
  position: relative;

  .icon_delete {
    position: absolute;
    left: 95px;
    top: 10px;
    cursor: pointer;
  }

  &.rew_wrapper {
    padding-left: 70px;
  }
}

.task_wrapper {
  display: flex;

  .row_add {
    margin-top: 4px;
  }
}

.sudoku_row {
  display: flex;
  align-items: center;
  width: 100%;
  flex-wrap: wrap;
}

.sudoku_item {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 25%;
  padding-top: 10px;
  padding-bottom: 10px;
}

.opacity {
  opacity: 0.4;
  background: #e5e5e5;
}

.sudoku_item img {
  margin-bottom: 3px;
  display: block;
}
</style>
